package tms

import (
	"fmt"
	"time"

	eventsV2 "github.com/cloudevents/sdk-go/v2"
	"github.com/google/uuid"
)

var (
	cloud        = "inspurcloud"
	productCode  = "fcs"
	source       = cloud + "." + productCode // 事件来源, 格式: 云固定前缀.产品
	ResourceECI  = "fcs"                     // FCS资源,目前仅此一种
	ActionDelete = "delete"                  // 删除操作
)

func NewEvent(a5tId, resource, action string, jsonObj interface{}) (*eventsV2.Event, error) {

	if len(region) == 0 {
		return nil, fmt.Errorf("newEvent: must invoke Init() first")
	}

	event := eventsV2.NewEvent(eventsV2.VersionV1)
	event.SetTime(time.Now().UTC())
	event.SetID(uuid.New().String())

	event.SetSource(source)
	event.SetSubject(buildSubject(region, resource, action))
	event.SetType(buildType(resource, action))

	event.SetExtension("productcode", productCode)
	event.SetExtension("region", region)
	event.SetExtension("cluster", cluster)
	event.SetExtension("resource", resource)
	event.SetExtension("accountid", a5tId)
	event.SetExtension("action", action)
	logger.Info("tms Content-Type")
	// 默认根据 Content-Type 选择序列化方法
	if err := event.SetData(eventsV2.ApplicationJSON, jsonObj); err != nil {
		return nil, err
	}
	return &event, nil
}

// buildSubject 构造主题, 格式:区域.产品.资源.操作
func buildSubject(region, resource, action string) string {
	return region + "." + productCode + "." + resource + "." + action
}

// buildType 构造操作类型, 格式:云固定前缀.产品代码.资源.操作
func buildType(resource, action string) string {
	return cloud + "." + productCode + "." + resource + "." + action
}
